package eerbaar.shared.persist.internal.lib;

import eerbaar.elements.ElementConstants;
import eerbaar.elements.IElement;
import eerbaar.elements.extension.ElementFactory;
import eerbaar.elements.extension.IPoints;
import eerbaar.position.IPosition;
import eerbaar.position.PositionConstants;
import eerbaar.shared.exceptions.GameRuntimeException;
import eerbaar.shared.persist.IPersister;
import eerbaar.shared.persist.ISaver;
import eerbaar.shared.tree.IAttributes;
import eerbaar.shared.tree.INode;
import eerbaar.shared.tree.NodeCmdFactory;

public class ElementPersister implements IPersister<IElement> {

    private IElement target;

    public ElementPersister() {
        //
    }

    public ElementPersister(IElement wrapper) {
        this.target = wrapper;
    }

    public ElementPersister(INode node) throws GameRuntimeException {
        load(node);
    }

    @Override
    public Class<IElement> getRegistertedInterface() {
        return IElement.class;
    }

    @Override
    public PositionPersister[] getSavableChildren() {
        PositionPersister p = new PositionPersister(this.target.getPosition());
        return new PositionPersister[] { p };
    }

    @Override
    public String getSavableName() {
        return ElementConstants.ELEMENT_NAME;
    }

    @Override
    public IElement getTarget() {
        return this.target;
    }

    @Override
    public boolean isAssignableFrom(ISaver<?> rsist) {
        return false;
    }

    @Override
    public IElement load(INode node) {
        IAttributes attributes = node.getAttributes();
        String name = attributes.get(String.class, ElementConstants.NAME);

        INode positionNode = NodeCmdFactory.findChild(node,
                PositionConstants.NAME);
        IPosition position = new PositionPersister().load(positionNode);

        int points = 0;
        if (attributes.get(ElementConstants.POINTS) != null) {
            points = attributes.get(Integer.class, ElementConstants.POINTS);
        }
        return ElementFactory.create(name, position, points);
    }

    @Override
    public void saveAttributes(INode node) {
        IAttributes attributes = node.getAttributes();
        attributes.set(String.class, ElementConstants.TYPE,
                ElementConstants.ELEMENT_NAME);
        attributes.set(String.class, ElementConstants.NAME,
                this.target.getName());
        IPoints points = this.target.getExtension(IPoints.class);
        if (points != null) {
            attributes.set(Integer.class, ElementConstants.POINTS,
                    points.getPoints());
        }
    }

    @Override
    public void setTarget(IElement obj) {
        this.target = obj;
    }

}
